//
//  BKDevAboutVC.m
//  BKDevMenu
//
//  Created by luzz on 2022/2/22.
//

#import "BKDevAboutVC.h"
#import <WebKit/WebKit.h>

static inline NSBundle *kGetBundle(Class aClass)
{
    NSBundle * mainBundle = [NSBundle bundleForClass:aClass];
    NSString * resourcePath = [mainBundle pathForResource:@"BKDevMenuBundle" ofType:@"bundle"];
    NSBundle *resourceBundle = [NSBundle bundleWithPath:resourcePath];
    return resourceBundle?:mainBundle;
}

@interface LZZQuickLoginGuideView : UIView <UIScrollViewDelegate>
@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, weak) UIPageControl *pageControl;
- (void)showOnView:(UIView *)view;
@end

@implementation LZZQuickLoginGuideView
{
    BOOL _animationing;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
        [self setupUI];
    }
    return self;
}


- (NSArray <UIImage *>*)getImages
{
    NSBundle *bundle = kGetBundle([self class]);
    NSString *filePath = [bundle pathForResource:@"guideData" ofType:@""];
    NSString *base64Str = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
    NSArray *imgsBase64Strs = [base64Str componentsSeparatedByString:@"\n"];
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:1];
    for (NSString *imgBase64Str in imgsBase64Strs) {
        if (imgBase64Str.length > 0) {
            NSData * showData = [[NSData alloc] initWithBase64EncodedString:imgBase64Str options:NSDataBase64DecodingIgnoreUnknownCharacters];
            if (showData) {
                UIImage *image = [UIImage imageWithData:showData];
                if (image) {
                    [images addObject:image];
                }
            }
            
        }
    }
    return images;
}



- (void)setupUI
{
    NSArray *images = [self getImages];
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    CGFloat w = CGRectGetWidth(self.frame);
    CGFloat h = CGRectGetHeight(self.frame);
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, h * 0.1, w, 0.8 * h)];
    scrollView.delegate = self;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    [self addSubview:scrollView];
    self.scrollView = scrollView;
    scrollView.pagingEnabled = YES;
    scrollView.contentSize = CGSizeMake(images.count * w, CGRectGetHeight(scrollView.frame));
    
    for (int i = 0; i < images.count; i++) {
        UIView *cell = [[UIView alloc] initWithFrame:CGRectMake(i * w, 0, w, CGRectGetHeight(scrollView.frame))];
        [scrollView addSubview:cell];

        UIImage *image = images[i];
        
        CGSize imgSize = CGSizeMake(w * 0.8, w * 0.8 * image.size.height / image.size.width);
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        imageView.frame = CGRectMake((CGRectGetWidth(cell.frame) - imgSize.width)/2.0, (CGRectGetHeight(cell.frame) - imgSize.height)/2.0, imgSize.width, imgSize.height);
        [cell addSubview:imageView];
    }
    
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(scrollView.frame), w, 40)];
    pageControl.numberOfPages = images.count;
    pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    pageControl.currentPageIndicatorTintColor = [UIColor systemRedColor];
    [self addSubview:pageControl];
    self.pageControl = pageControl;
    
    
}

- (void)showOnView:(UIView *)view
{
    
    for (UIView *subView in view.subviews) {
        if ([subView isKindOfClass:[LZZQuickLoginGuideView class]]) {
            [subView removeFromSuperview];
        }
    }
    
    self.frame = view.bounds;
    self.alpha = 0;
    [view addSubview:self];
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1.0;
    }];
}

- (void)hideFromView
{
    if (_animationing) {
        return;
    }
    _animationing = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hideFromView];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"%f",scrollView.contentOffset.x);
    self.pageControl.currentPage = round(scrollView.contentOffset.x/CGRectGetWidth(scrollView.frame));
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x > (scrollView.contentSize.width - CGRectGetWidth(scrollView.frame) + 30.0)) {
        [self hideFromView];
    }
}

@end



@interface BKDevAboutVC () <WKNavigationDelegate>
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic,weak) UIView *progressView;
@property (nonatomic,weak) CALayer *progressLayer;
@end

@implementation BKDevAboutVC



- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"关于BKDevMenu";
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    [self setupProgress];
    
    NSBundle * bundle = kGetBundle([self class]);
    NSString *htmlPath = [bundle pathForResource:@"About" ofType:@"html"];
    NSString *htmlStr = [[NSString alloc] initWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:NULL];
    
//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://gitee.com/luzizheng/BKDevMenu"]]];
    [self.webView loadHTMLString:htmlStr baseURL:nil];

    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    if ([url.scheme isEqualToString:@"mailto"]) {
        if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
            if (@available(iOS 10.0, *)) {

                [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:^(BOOL success) {
                    NSLog(@"%@",success?@"success":@"failed");
                }];
            } else {
                [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            }
        }
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }else if([url.scheme isEqualToString:@"guideto"]){
        [self showGuide];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (void)showGuide
{
    LZZQuickLoginGuideView *guideView = [[LZZQuickLoginGuideView alloc] init];
    [guideView showOnView:self.navigationController.view];
}


- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.webView.frame = self.view.bounds;
    CGFloat top = 0;
    if (@available(iOS 11.0, *)) {
        top = self.webView.scrollView.adjustedContentInset.top;
    } else {
        top = [UIApplication sharedApplication].statusBarFrame.size.height + self.navigationController.navigationBar.frame.size.height;
    }
    self.progressView.frame = CGRectMake(0, top, CGRectGetWidth(self.view.frame), 3);
}

-(void)setupProgress{
    UIView *progress = [[UIView alloc] init];
    progress.backgroundColor = [UIColor  clearColor];
    [self.view addSubview:progress];
    self.progressView = progress;
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 3);
    layer.backgroundColor = [UIColor systemOrangeColor].CGColor;
    [progress.layer addSublayer:layer];
    self.progressLayer = layer;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressLayer.opacity = 1;
        if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
            return;
        }
        self.progressLayer.frame = CGRectMake(0, 0, self.view.frame.size.width*[change[@"new"] floatValue], 3);
        if ([change[@"new"]floatValue] == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressLayer.opacity = 0;
                self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }
}



@end
